/**
 * 层级处理
 * @param {*} routers 原始路由数据
 */
function getPureRouter(routers) {
  return routers.map(item => {
    let levelUpItems = []
    // 获取一级路由 children 中 levelUp 为 true 的元素
    levelUpItems = item.children?.filter(child => child.meta?.levelUp)
    // 只有当需要提升的元素个数为 1 时，才认为该一级路由在侧边栏上不需要展示层级
    const { levelUp, ...metaRest } = item.meta || {} // eslint-disable-line
    if (levelUpItems?.length === 1) {
      const levelUpEle = levelUpItems[0]
      const { levelUp, ...metaRest2 } = levelUpEle.meta || {} // eslint-disable-line
      const meta = { ...metaRest, ...metaRest2 }
      const { children, ...rest2 } = levelUpEle // eslint-disable-line
      item = { ...item, ...rest2, meta, levelUp: true }
      item.children = item.children.filter(it => it.path !== levelUpEle.path)
    }
    return item
  })
}

/**
 * 将路由转换成侧边栏需要的数据格式
 * @param {*} router 路由
 * @param {*} deep 深度
 * @returns [{title:"", path:"", deep:number, icon:"", children:[]}]
 */
function transformMenu(router, deep) {
  let menus = []
  router.forEach(item => {
    const notOnMenu = !!item.meta?.notOnMenu // 不展示在菜单上
    if (notOnMenu) return
    let obj = {
      title: item.meta ? item.meta.title : '',
      icon: item.meta?.icon || '',
      path: item.path,
      deep,
    }
    if (item.children && item.children.length) {
      obj.children = transformMenu(item.children, deep + 1)
    }
    menus.push(obj)
  })
  return menus
}

/**
 * 将路由转换成面包屑需要的数据格式
 * @param {*} router 路由
 * @param {*} parentBreadcrumb 父节点  [{title:"角色",path:""},{title:"角色列表",path:"/role/list"}]
 * @param {*} result 最终结果
 * @param {*}  isRoot 是否根节点
 * @returns
 */
function getBreadcrumb(router, parentBreadcrumb, result) {
  router.forEach(item => {
    const hasChildren = item.children?.length
    const path = hasChildren && !item.levelUp ? '' : item.path // 有孩子的是不可以被点击的，直接将路径置空
    const title = item.meta?.title || ''
    const curBreadcrumb = [{ path: path, title: title }] // [{title:"新增角色",path:"/role/add"}]
    const b = parentBreadcrumb.concat(curBreadcrumb)
    if (hasChildren) {
      getBreadcrumb(item.children, b, result, false)
    }
    if (path) {
      result.push({
        breadcrumb: b,
        path,
      })
    }
  })
  return result
}
export default {
  namespaced: true,
  state: {
    pureRouters: [],
    menuList: [], // 侧边栏菜单数据
    breadcrumbList: [], // 面包屑数据
    collapse: false, // 侧边栏是否收起
  },
  mutations: {
    /** 设置侧边栏数据 */
    SET_SIDEBAR_MENU: state => {
      state.menuList = transformMenu(state.pureRouters, 0)
    },
    /** 设置面包屑数据 */
    SET_BREADCRUMB: state => {
      state.breadcrumbList = getBreadcrumb(state.pureRouters, [], [])
    },
    SET_SIDEBAR_COLLAPSE: (state, payload) => {
      state.collapse = payload
    },
  },
  actions: {
    SET_PURE_ROUTER: ({ state }, payload) => {
      state.pureRouters = getPureRouter(payload)
    },
  },
}
